/**
 * mini (~500 b) version for event-emitter.
 *
 * Created by hustcc on 2018/12/31
 * Contract: vip@hust.edu.cn
 */

export interface Listener {
  cb: Function;
  once: boolean;
  target: object;
}

export interface EventsType {
  [eventName: string]: Listener[];
}

export default class OnFire {

  static ver = '__VERSION__';

  // 所有事件的监听器
  es: EventsType = {};

  on(eventName: string, cb: Function, target: object) {
    if (!this.es[eventName]) {
      this.es[eventName] = [];
    }

    this.es[eventName].push({
      cb,
      once: false,
      target,
    });
  }

  once(eventName: string, cb: Function, target: object) {
    if (!this.es[eventName]) {
      this.es[eventName] = [];
    }

    this.es[eventName].push({
      cb,
      once: true,
      target,
    });
  }

  fire(eventName: string, params: any) {
    const listeners = this.es[eventName] || [];
    
    let l = listeners.length;

    for (let i = 0; i < l; i++) {
      const { cb, once, target } = listeners[i];
      let args = [eventName, params];
      cb.apply(target, args);

      if (once) {
        listeners.splice(i, 1);
        i--;
        l--;
      }
    }
  }

  off(eventName?: string, cb?: Function, target?: object) {
    // clean all
    if (eventName === undefined) {
      this.es = {};
    } else {
      if (cb === undefined) {
        // clean the eventName's listeners
        delete this.es[eventName];
      } else if (cb === null) {
        if (!target) {
          return;
        }
        const listeners = this.es[eventName] || [];
        // clean the event and listener
        let l = listeners.length;
        for (let i = 0; i < l; i++) {
          if (listeners[i].target === target) {
            listeners.splice(i, 1);
            i--;
            l--;
          }
        }
      } else {
        const listeners = this.es[eventName] || [];
        // clean the event and listener
        let l = listeners.length;
        for (let i = 0; i < l; i++) {
          if (listeners[i].cb === cb && listeners[i].target === target) {
            listeners.splice(i, 1);
            i--;
            l--;
          }
        }
      }
    }
  }

  // cname of fire
  emit(eventName: string, params: any) {
    this.fire(eventName, params);
  }
}